# -*- coding:utf-8 -*-
import struct,codecs,re,Pluto,fnmatch

#利用码表生成字典
def makedic():
    dic={}
    tbl=codecs.open('in.tbl','r+b','utf_16')
    for line in tbl:
        line_split=line.replace('\r\n','').split(u'=')
        dic[line_split[1]]=line_split[0].lower()
    tbl.close()
    return dic

mydic=makedic()

#将几行文本合成
def makestr(i):
    string=''
    j=0
    while j>=0:

        #匹配文本结束标志
        if re.match(u'－'*18,text[i+2+j]):
            break

        string+=text[i+2+j]
        j+=1
    return string[:-2]

#写入单字节
def bytewrite(string,j):
    return chr(int(mydic[string[j]],16))

#写入unicode字符
def wordwrite(string,j):
    return chr(int(mydic[string[j]][:2],16))+chr(int(mydic[string[j]][2:4],16))

def counter(string):
    count=0
    j=0
    while j<len(string):
        if ord(string[j])==13:
            count+=1

        #如果字符在字典里面，则导入
        if string[j] in mydic:

            if len(mydic[string[j]])==4:
                count+=2

            if len(mydic[string[j]])==2:
                count+=1
        j+=1
    return count

def writer(string):
    j=0
    while j<len(string):
        #如果字符在字典里面，则导入
        if string[j] in mydic:

            if len(mydic[string[j]])==4:
                target.write(wordwrite(string,j))

            if len(mydic[string[j]])==2:
                target.write(bytewrite(string,j))
            j+=1
        else:
            print string[j],'not in dic!'
            j+=1
    if target.tell()%2==0:
        target.write('\x00\x00')
    else:
        target.write('\x00')

fl=Pluto.walk('script')

for fn in fl:
    if not fnmatch.fnmatch(fn,'*.txt'):
        continue
    if '.scripb' in fn:
        continue
    print fn
    fp=codecs.open(fn,'rb','utf16')
    text=fp.readlines()
    fp.close()
    line_num=len(text)
    
    text_list=[]
    for i in xrange(line_num):
        if re.match('No.\d+',text[i]):
            text_list.append(makestr(i))
    text_len=len(text_list)

    target=open(fn[:-4],'wb')
    target.write('DNGC')
    target.write(struct.pack('i',text_len))
    target.seek(8+text_len*4)

    offset_list=[]
    for string in text_list:
        #print string
        offset_list.append(target.tell())
        lines=string.split('\r\n')
        upline=lines[0]
        downline=lines[1]
        target.write(struct.pack('H',counter(upline)+1))
        writer(upline)
        target.write(struct.pack('H',counter(downline)+1))
        writer(downline)
    target.seek(8)
    for offset in offset_list:
        target.write(struct.pack('i',offset))
    target.close()
